<template>
  <div class="article-management">
    <a-card title="文章管理" :bordered="false">
      <template #extra>
        <a-button type="primary" @click="showModal">
          <template #icon><plus-outlined /></template>
          新建文章
        </a-button>
      </template>

      <a-table
        :columns="columns"
        :data-source="articleList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #empty>
          <div class="empty-text">
            <p>暂无文章</p>
            <a-button type="primary" @click="showModal">
              <template #icon><plus-outlined /></template>
              创建第一篇文章
            </a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleView(record)">查看</a>
              <a-divider type="vertical" />
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleDownload(record)">下载</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这篇文章吗？"
                @confirm="handleDelete(record)"
              >
                <a class="text-red-500">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 'published' ? 'green' : 'orange'">
              {{ record.status === 'published' ? '已发布' : '草稿' }}
            </a-tag>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新建/编辑文章对话框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="1000px"
      :maskClosable="false"
    >
      <a-form :model="articleForm" :rules="rules" ref="articleFormRef">
        <a-form-item label="标题" name="title">
          <a-input v-model:value="articleForm.title" placeholder="请输入文章标题" />
        </a-form-item>
        <a-form-item label="作者" name="author">
          <a-input v-model:value="articleForm.author" placeholder="请输入作者" />
        </a-form-item>
        <a-form-item label="内容" name="content">
          <MdEditor
            v-model="articleForm.content"
            :toolbars="toolbars"
            :preview="true"
            :previewTheme="previewTheme"
            :showCodeRowNumber="true"
            :toolbarsExclude="['github']"
            @onChange="handleEditorChange"
            style="height: 500px"
          />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="articleForm.status">
            <a-select-option value="draft">草稿</a-select-option>
            <a-select-option value="published">发布</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { PlusOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import { anyHttpClient } from '@/network'
import { useRouter } from 'vue-router'
import { MdEditor, type ToolbarNames } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

interface ArticleItem {
  id: number
  title: string
  author: string
  createTime: string
  status: 'published' | 'draft'
  content: string
}

const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '作者',
    dataIndex: 'author',
    key: 'author',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '操作',
    key: 'action',
  },
]

const loading = ref(false)
const articleList = ref<ArticleItem[]>([])
const pagination = ref<TablePaginationConfig>({
  total: 0,
  current: 1,
  pageSize: 10,
})

const modalVisible = ref(false)
const modalTitle = ref('新建文章')
const articleFormRef = ref()
const articleForm = ref({
  id: undefined as number | undefined,
  title: '',
  author: '',
  content: '',
  status: 'draft' as 'draft' | 'published'
})

// Markdown 编辑器配置
const toolbars: ToolbarNames[] = [
  'bold',
  'underline',
  'italic',
  'strikeThrough',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  'codeRow',
  'code',
  'link',
  'image',
  'table',
  'revoke',
  'next',
  'save',
  'fullscreen',
  'preview',
  'htmlPreview',
  'catalog'
]

const previewTheme = 'default'

const handleEditorChange = (value: string) => {
  articleForm.value.content = value
}

const rules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const router = useRouter()

const fetchArticleList = async () => {
  loading.value = true
  try {
    const response = await anyHttpClient.get('/api/article/list')
    // 响应拦截器已经处理了 ApiResponse 格式，直接使用 response.data
    if (response.data && Array.isArray(response.data)) {
      articleList.value = response.data
      pagination.value.total = response.data.length
    } else {
      articleList.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    articleList.value = []
    pagination.value.total = 0
    message.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

const handleTableChange = (pag: TablePaginationConfig) => {
  pagination.value = pag
  fetchArticleList()
}

const showModal = () => {
  modalTitle.value = '新建文章'
  articleForm.value = {
    id: undefined,
    title: '',
    author: '',
    content: '',
    status: 'draft'
  }
  modalVisible.value = true
}

const handleEdit = (record: ArticleItem) => {
  modalTitle.value = '编辑文章'
  articleForm.value = { ...record }
  modalVisible.value = true
}

const handleModalOk = async () => {
  try {
    await articleFormRef.value.validate()
    if (articleForm.value.id) {
      // 更新文章
      await anyHttpClient.put(`/api/article/${articleForm.value.id}`, articleForm.value)
      message.success('更新成功')
    } else {
      // 创建文章
              await anyHttpClient.post('/api/article', articleForm.value)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchArticleList()
  } catch (error) {
    message.error('操作失败')
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  articleFormRef.value?.resetFields()
}

const handleView = (record: ArticleItem) => {
  router.push(`/article/detail/${record.id}`)
}

const handleDownload = async (record: ArticleItem) => {
  try {
    const response = await anyHttpClient.get(`/api/article/${record.id}/download`, {
      responseType: 'blob'
    })
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `${record.title}.md`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    message.error('下载失败')
  }
}

const handleDelete = async (record: ArticleItem) => {
  try {
          await anyHttpClient.delete(`/api/article/${record.id}`)
    message.success('删除成功')
    fetchArticleList()
  } catch (error) {
    message.error('删除失败')
  }
}

onMounted(() => {
  fetchArticleList()
})
</script>

<style scoped>
.article-management {
  padding: 24px;
}

.empty-text {
  text-align: center;
  padding: 32px 0;
}

.empty-text p {
  margin-bottom: 16px;
  color: rgba(0, 0, 0, 0.45);
}

:deep(.md-editor) {
  border: 1px solid #d9d9d9;
  border-radius: 2px;
}

:deep(.md-editor:hover) {
  border-color: #40a9ff;
}

:deep(.md-editor:focus-within) {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}
</style>